import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginRequest, getProfileRequest } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

export default {
  // namespaced 就表示当前文件是一个 vuex的子模块，加入到其他文件的modules里面去
  namespaced: true,
  // token持久化的方案： localStorage sessionStorage cookies
  state: {
    token: getToken(),
    userInfo: {},
    routes: []
  },
  getters: {},
  mutations: {
    setTokenMutation(state, payload) {
      state.token = payload
      setToken(payload)
    },
    removeTokenMutation(state) {
      state.token = undefined
      removeToken()
    },
    setUserInfoMutation(state, payload) {
      state.userInfo = payload
    },
    removeUserInfoMutation(state) {
      state.userInfo = {}
    },
    setRoutesMutation(state, payload) {
      state.routes = [...constantRoutes, ...payload]
    }
  },
  actions: {
    async setTokenAction(context, payload) {
      const res = await loginRequest(payload)
      //
      context.commit('setTokenMutation', res.data)
      return res
    },
    logoutAction(context) {
      context.commit('removeTokenMutation')
      context.commit('removeUserInfoMutation')
      // 清空动态路由
      resetRouter()
    },
    async setUserInfoAction(context, payload) {
      const res = await getProfileRequest()
      // conslo.log(res)
      context.commit('setUserInfoMutation', res.data)
      return res.data
    }
  }
}
